/**
 * 用户交互模块
 * 
 * 包含所有与用户交互相关的函数
 */


import inquirer from 'inquirer';
const { prompt } = inquirer;
import { existsSync } from 'fs';

import { join } from 'path';
import { printColored, validatePackageName, validateProjectName } from './utils.js';



/**
 * 用户交互功能集合
 */
export const getUserInteraction = {
  /**
   * 获取项目类型
   * 
   * @returns {Promise<string>} 'app' 或 'module'
   */
  getProjectType: async () => {

    const { projectType } = await prompt([
      {
        type: 'list',
        name: 'projectType',
        message: '请选择项目类型:',
        choices: [
          { name: '应用 (app)', value: 'app', },
          { name: '模块 (module)', value: 'module', },
          { name: '原生插件 (plugin)', value: 'plugin', },
          { name: '插件 (package)', value: 'package', }
        ],
        default: 'app'
      }
    ]);
    return projectType;
  },

  /**
   * 获取模板类型
   * 
   * @returns {Promise<string>} 'only' 或 'min' 或 'normal' 或 'pro'
   */
  getTemplateType: async () => {



    const { templateType } = await prompt([
      {
        type: 'list',
        name: 'templateType',
        message: '请选择项目模版:',
        choices: [
          { name: 'only (main.dart)', value: 'only' },
          { name: 'min (项目结构、路由管理、主题管理、状态管理、工具集)', value: 'min' },
          { name: 'normal (项目结构、路由管理、主题管理、状态管理、工具集、UI组件库)', value: 'normal' },
          { name: 'pro (项目结构、路由管理、主题管理、状态管理、工具集、UI组件库、网络请求、数据缓存、示例模块)', value: 'pro' }
        ],
        default: 'pro'
      }
    ]);
    return templateType;
  },

  /**
   * 获取状态管理
   * 
   * @returns {Promise<string>} 'state' 或 'GetX'  
   */
  getStateManager: async () => {
    const { stateManager } = await prompt([
      {
        type: 'list',
        name: 'stateManager',
        message: '请选择状态管理:',
        choices: [
          { name: 'state (State)', value: 'state' },
          { name: 'get (GetX)', value: 'GetX' },
        ],
        default: 'state'
      }
    ]);
    return stateManager;
  },

  getIsNeedDemo: async () => {
    const { isNeedDemo } = await prompt([
      {
        type: 'confirm',
        name: 'isNeedDemo',
        message: '是否需要使用事例:',
        default: true
      }
    ])
    return isNeedDemo;
  },

  /**
   * 获取项目信息
   * 
   * @param {string} projectType - 项目类型 ('app'或'module')
   * @param {string} defaultProjectName - 默认项目名称
   * @param {string} defaultPackageName - 默认包名
   * @param {string} defaultParentDir - 默认父目录
   * @returns {Promise<Object>} 项目信息对象
   */
  getProjectInfo: async (projectType, defaultProjectName, defaultPackageName, defaultParentDir, flutterSdkPath) => {
    // 获取项目名称
    let projectName = defaultProjectName;
    if (!defaultProjectName) {
      defaultProjectName = getDefaultProjectName(projectType);
      const res = await prompt([
        {
          type: 'input',
          name: 'projectName',
          message: '请输入新项目名称（小写字母、数字和下划线）:',
          default: defaultProjectName,
          validate: validateProjectName
        }

      ]);
      projectName = res.projectName;
    }

    // 获取Flutter SDK路径
    if (!flutterSdkPath) {
      flutterSdkPath = await getFlutterSdkPath();
    }
    // 获取包名
    let packageName = defaultPackageName;
    if (!defaultPackageName) {
      defaultPackageName = `com.example.${projectName}`;
      const res = await prompt([
        {
          type: 'input',
          name: 'packageName',
          message: '请输入包名:',
          default: defaultPackageName || `com.example.${projectName}`,
          validate: validatePackageName
        }
      ]);
      packageName = res.packageName;
    }



    // 获取父目录
    let parentDir = defaultParentDir;
    if (!defaultParentDir) {
      defaultParentDir = process.cwd();
      const res = await prompt([
        {
          type: 'input',
          name: 'parentDir',
          message: '请输入项目存放路径:',
          default: defaultParentDir
        }
      ]);
      parentDir = res.parentDir;
    }

    const targetDir = join(parentDir, projectName);
    console.log('flutterPath:', flutterSdkPath);
    return {
      projectName,
      packageName,
      parentDir,
      targetDir,
      flutterSdkPath
    };
  },

  /**
   * 确认是否覆盖已存在的目录
   * 
   * @param {string} targetDir - 目标目录路径
   * @returns {Promise<boolean>} 是否覆盖
   */
  confirmOverwrite: async (targetDir) => {
    printColored(`\n警告: 目标目录 ${targetDir} 已存在!`, 'yellow');

    const { overwrite } = await prompt([
      {
        type: 'confirm',
        name: 'overwrite',
        message: '是否覆盖？',
        default: false
      }
    ]);

    if (overwrite) {
      printColored("将覆盖目标目录", 'red');
    } else {
      printColored("操作已取消", 'green');
    }

    return overwrite;
  },

  /**
   * 获取用户选择的IDE类型
   * 
   * @returns {Promise<string>} IDE类型
   */
  getIdeChoice: async () => {
    const { ideChoice } = await prompt([
      {
        type: 'list',
        name: 'ideChoice',
        message: '请选择要打开项目的IDE:',
        choices: [
          { name: 'Visual Studio Code', value: 'vscode' },
          { name: 'Android Studio', value: 'android_studio' },
          { name: '打开文件夹', value: 'open_folder' },
          { name: '不打开', value: 'manual' }
        ],
        default: 'vscode'
      }
    ]);

    return ideChoice;
  }
};

async function getFlutterSdkPath () {
  const { path: sdkPath } = await prompt([{
    type: 'input',
    name: 'path',

    message: '请输入Flutter SDK路径（留空使用系统默认）:',
    validate: input => !input || existsSync(join(input, 'bin/flutter'))
  }]);
  return sdkPath || 'flutter';
}

/**
 * 获取默认项目名称
 * 
 * @param {string} projectType - 项目类型 ('app'或'module')
 * @returns {string} 默认项目名称
 */
function getDefaultProjectName (projectType) {
  let defaultProjectName = 'project';
  switch (projectType) {
    case 'app':
      defaultProjectName = 'project';
      break;
    case 'module':
      defaultProjectName = 'module';
      break;
    case 'package':
      defaultProjectName = 'package';
      break;
    case 'plugin':
      defaultProjectName = 'plugin';
      break;
    default:
      defaultProjectName = 'example';
      break;
  }
  return "hzy_example_" + defaultProjectName;
}

export default {
  getFlutterSdkPath,
  getDefaultProjectName,
  getUserInteraction
};
